import React, { useEffect, useRef, useState } from 'react';
import Peer from 'simple-peer';

const VideoCall = () => {
    const [isCallStarted, setIsCallStarted] = useState(false);
    const [peer, setPeer] = useState(null);
    const [stream, setStream] = useState(null);
    const userVideoRef = useRef(null);
    const peerVideoRef = useRef(null);
    const socket = useRef(null);

    useEffect(() => {
        // 获取用户媒体（视频和音频）
        navigator.mediaDevices
            .getUserMedia({ video: true, audio: false })
            .then((mediaStream) => {
                setStream(mediaStream);
                if (userVideoRef.current) {
                    userVideoRef.current.srcObject = mediaStream;
                }
            })
            .catch((err) => {
                console.error('Error accessing media devices.', err);
            });

        // 初始化 WebSocket 连接
        socket.current = new WebSocket('ws://localhost:8082');
        socket.current.onmessage = (event) => {
            const signalData = JSON.parse(event.data);
            console.log('Received signal data:', signalData); // Debugging signal data
            if (signalData.type === 'offer') {
                joinCall(signalData);
            } else if (signalData.type === 'answer' && peer) {
                console.log('Sending answer signal to peer');
                peer.signal(signalData);
            } else if (signalData.type === 'candidate' && peer) {
                console.log('Sending candidate signal to peer');
                peer.signal(signalData);
            }
        };

        // 清理工作
        return () => {
            if (stream) {
                stream.getTracks().forEach((track) => track.stop());
            }
            if (socket.current) {
                socket.current.close();
            }
        };
    }, []);

    const startCall = () => {
        const p = new Peer({
            initiator: true,
            trickle: false,
            stream: stream,
        });

        p.on('signal', (data) => {
            console.log('Signal data (offer):', data); // Debugging signal data
            if (socket.current) {
                socket.current.send(JSON.stringify(data));
            }
        });

        p.on('stream', (remoteStream) => {
            console.log('Remote stream received:', remoteStream); // Debugging remote stream
            if (peerVideoRef.current) {
                peerVideoRef.current.srcObject = remoteStream;
            }
        });

        p.on('error', (err) => {
            console.error('Peer connection error:', err); // Debugging peer errors
        });

        setPeer(p);
        setIsCallStarted(true);
    };

    const joinCall = (signalData) => {
        const p = new Peer({
            initiator: false,
            trickle: false,
            stream: stream,
        });

        p.on('signal', (data) => {
            console.log('Signal data (answer):', data); // Debugging signal data
            if (socket.current) {
                socket.current.send(JSON.stringify(data));
            }
        });

        p.on('stream', (remoteStream) => {
            console.log('Remote stream received in joinCall:', remoteStream); // Debugging remote stream
            if (peerVideoRef.current) {
                peerVideoRef.current.srcObject = remoteStream;
            }
        });

        p.on('error', (err) => {
            console.error('Peer connection error in joinCall:', err); // Debugging peer errors
        });

        p.signal(signalData);

        setPeer(p);
        setIsCallStarted(true);
    };


    return (
        <div>
            <h2>React WebRTC Video Call</h2>
            <div style={{ display: 'flex' }}>
                <div>
                    <h3>User A (Your Video)</h3>
                    <video
                        ref={userVideoRef}
                        autoPlay
                        muted
                        style={{ width: '300px', height: '200px' }}
                    />
                </div>
                <div>
                    <h3>User B (Peer's Video)</h3>
                    <video
                        ref={peerVideoRef}
                        autoPlay
                        style={{ width: '300px', height: '200px' }}
                    />
                </div>
            </div>
            <div>
                {!isCallStarted ? (
                    <>
                        <button onClick={startCall}>Start Call (User A)</button>
                        {/* 用户B可以通过某种方式发送 signal 数据，例如通过按钮 */}
                    </>
                ) : (
                    <p>Call in progress...</p>
                )}
            </div>
        </div>
    );
};

export default VideoCall;
